<template>
    <el-dialog v-model="show" :show-close="false" width="500" center align-center class="batch-pay-dialog"
        @close="close">
        <template #title>
            <custom-title title="充值" />
        </template>
        <el-form label-width="120" :model="form" :rules="payRules" ref="formRef">
            <el-form-item label="我的账户" prop="payMemberId">
                <div class="readonly">{{ currentAccountData.memberName }}</div>
            </el-form-item>
            <el-form-item label="付款方式" prop="paymentMethod">
                <el-radio-group v-model="form.paymentMethod" @change="getBankCardList">
                    <el-radio value="BANK" label="网银支付" v-if="currentAccountData.memberType!=1"></el-radio>
                    <el-radio value="QUICK_PAY" label="快捷支付" v-if="showShortcut"></el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="充值金额" prop="rechargeAmount">
                <el-input v-model="form.rechargeAmount" placeholder="请输入"></el-input>
            </el-form-item>
            <template v-if="form.paymentMethod === 'BANK'">
                <el-form-item label="银行" prop="bankId">
                    <el-select-v2 v-model="form.bankId" filterable remote :remote-method="searchBank" clearable
                        :options="bankList" placeholder="请输入" style="flex: 1;" :props="prop" />
                </el-form-item>
                <el-form-item label="账户类型" prop="bankAccountType" v-if="currentAccountData.memberType == 3">
                    <el-radio-group v-model="form.bankAccountType">
                        <el-radio label="个人账号" value="INDIVIDUAL"></el-radio>
                        <el-radio label="企业账户" value="ENTERPRISE"></el-radio>
                    </el-radio-group>
                </el-form-item>
            </template>
            <template v-if="form.paymentMethod === 'QUICK_PAY'">
                <el-form-item label="银行卡号" prop="bankCardNo">
                    <el-select v-model="form.bankCardNo" @change="setMobile">
                        <el-option v-for="item in bankCardList" :label="`${item.bankName} - ${item.cardNo}`"
                            :value="item.cardNo"></el-option>
                    </el-select>
                </el-form-item>
            </template>
            <template v-if="form.bankCardNo && form.paymentMethod === 'QUICK_PAY'">
                <el-form-item label="银行预留手机号">
                    <div class="readonly">{{ form?.mobile }}</div>
                </el-form-item>
                <el-form-item label="验证码">
                    <div class="space">
                        <el-input placeholder="请输入" v-model="form.verificationCode" />
                        <el-button type="primary" v-if="!sendCodeStatus.status" @click="launch">获取验证码</el-button>
                        <el-button v-else>重新获取({{ sendCodeStatus.time }}s)</el-button>
                    </div>
                </el-form-item>
            </template>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="show = false">取消</el-button>
                <el-button type="primary" @click="launch" v-if='form.paymentMethod == "BANK"'>
                    确定
                </el-button>
                <el-button type="primary" @click="comfirm" v-else>
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, computed } from "vue";
import { getWithdrawAccountList, getSupportBankList, recharge } from "@/apis/purse";
import { comfirmPay } from "@/apis/online";
import { onMounted } from "vue";
import { required, code } from "../../rules";
import { ElMessage } from "element-plus";
import { watch } from "vue";

const props = defineProps({
    modelValue: {
        type: Boolean,
        default: false
    },
    currentAccountData: {
        type: Object,
        required: true
    }
})
const emit = defineEmits(['update:modelValue', 'finish']);
const show = computed({
    get() {
        return props.modelValue
    },
    set(val) {
        emit('update:modelValue', val)
    }
})
const form = ref({});
const formRef = ref()
const payRules = {
    verificationCode: [
        required('请输入验证码'),
        code(6)
    ],
    paymentMethod: [
        required('请选择付款方式'),
    ],
    bankCardType: [
        required('请选择账户类型'),

    ],
    bankId: [
        required('请选择银行'),
    ],
    bankCardNo: [
        required('请选择银行卡号'),
    ],
    rechargeAmount: [
        required('请输入充值金额'),
        { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: '请输入正确的金额', trigger: 'blur' }
    ],
}
/**
 * 模糊查询银行
 */
 const searchBank = (key) => {
    keyword.value = key;
}
const prop = {
    value: 'bankCode',
    label: 'bankName'
}
const close = () => {
    form.value = {};
    formRef.value.resetFields()
}
const bankListData = ref([])
/**
 * 可用银行列表
 */
const bankList = computed(() => bankListData.value.filter(item => item.bankName.indexOf(keyword.value) !== -1))
const showShortcut = computed(() => {
    if (props.currentAccountData.memberType == 2) {
        return false;
    } else {
        return true;
    }
})
const bankCardList = ref([])

/**
 * 验证码当前状态
 */
const sendCodeStatus = ref({
    status: false,
    time: 60,
    timer: null
})
/**
 * 重置倒计时
 */
const clearTimer = () => {
    sendCodeStatus.value.status = false;
    clearInterval(sendCodeStatus.value.timer);
    sendCodeStatus.value.time = 60;
}
/**
 * 发送验证码之后的回调
 */
const sendCodeCallback = () => {
    sendCodeStatus.value.status = true;
    sendCodeStatus.value.timer = setInterval(() => {
        sendCodeStatus.value.time--;
        if (sendCodeStatus.value.time <= 0) {
            clearTimer()
        }
    }, 1000)
}
/**
 * 获取银行卡列表
 */
const getBankCardList = async () => {
    if (form.value.paymentMethod != 'QUICK_PAY') return;
    try {
        const res = await getWithdrawAccountList({ walletId: props.currentAccountData.walletId, accountType: 'INDIVIDUAL' });
        bankCardList.value = res.data
    } catch (error) {
        console.log(error)
    }
}
const keyword = ref('')
/**
 * 获取可用银行列表
 */
const getBankList = async () => {
    try {
        const res = await getSupportBankList()
        bankListData.value = res.data;
    } catch (error) {

    }
}
const setMobile = () => {
    const currentBankCard = bankCardList.value.find(v => v.cardNo === form.value.bankCardNo);
    form.value.mobile = currentBankCard.cardTel
}
const comfirm = () => {
    formRef.value.validate(async (valid) => {
        if (!valid) return;
        try {
            await comfirmPay({ capitalRecordId: capitalRecordId.value, verificationCode: form.value.verificationCode, transactionType: "RECHARGE" });
            ElMessage.success('支付成功')
            show.value = false;
            emit('flushed', (list) => {
                return list.filter(v => v.memberId == props.currentAccountData.memberId)[0];
            });
            clearTimer()
        } catch (error) {
            console.log(error)
        }
    })
}
const capitalRecordId = ref('')
const launch = async () => {
    formRef.value.validate(async (valid) => {
        if (!valid) return;
        const { walletId, memberId } = props.currentAccountData;
        try {
            const res = await recharge({ ...form.value, walletId, memberId });
            if (res.data.paymentInfo) {
                window.open(res.data.paymentInfo);
                show.value = false;
                return;
            }
            sendCodeCallback()
            ElMessage.success('发送成功')
            capitalRecordId.value = res.data.capitalRecordId;
        } catch (error) {
        }
    })
}
watch(() => props.currentAccountData.memberType, () => {
    if (props.currentAccountData.memberType == 1) {
        form.value.bankAccountType = 'INDIVIDUAL'
    } else if (props.currentAccountData.memberType == 2) {
        form.value.bankAccountType = 'ENTERPRISE'
    }
})
onMounted(() => {
    getBankList()
})
</script>

<style lang="scss" scoped></style>